package com.hsnn.medstgmini.base.dict.dao.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.hsnn.medstgmini.base.dict.dao.DicEntprodProfileDao;
import com.hsnn.medstgmini.base.dict.model.DicEntprodProfile;
import com.hsnn.medstgmini.dao.impl.HibernateSqlUtilImpl;
import com.hsnn.medstgmini.util.Pagination;

/**
 * @category 企业产品资质 类型
 * @author 王炳
 * @date 2015年7月13日
 */
@Repository
public class DicEntprodProfileDaoImpl extends BaseHibernateDAO implements DicEntprodProfileDao {
	
	@Resource(name = "sessionFactory")
	private SessionFactory sessionFactory;
	
	@Autowired
	private HibernateSqlUtilImpl dao;
	
	/**
	 * @category 获取企业产品资质 类型列表
	 * @date 2015年7月13日
	 * @return page
	 */
	@Override
	public Pagination getDicEntprodProfileList(Pagination page){
		
		String indiName = page.getConditions().get("indiName");
		String status = page.getConditions().get("status");
		StringBuffer sql = new StringBuffer();
		StringBuffer sqlSubfix = new StringBuffer();
		sql.append(" select d.dic_entprod_profile_id dicEntprodProfileId,d.first_level_indi_code firstLevelIndiCode,d.first_level_indi_name firstLevelIndiName,d.status status");
		sqlSubfix.append(" from dic_entprod_profile d where 1=1 ");
		if(StringUtils.isNotBlank(indiName)){
			sqlSubfix.append(" and d.first_level_indi_name like :indiName ");
		}
		
		if(StringUtils.isNotBlank(status)){
			sqlSubfix.append(" and d.status = :status ");
		}
		
		Query query = getSession().createSQLQuery(sql.append(sqlSubfix).toString());
		StringBuffer hqlCount = new StringBuffer();
		hqlCount.append(" select count(*) ").append(sqlSubfix);
		Query queryCount = getSession().createSQLQuery(hqlCount.toString());
		if(StringUtils.isNotBlank(indiName)){
			query.setString("indiName", "%" + indiName + "%");
			queryCount.setString("indiName", "%" + indiName + "%");
		}

		if(StringUtils.isNotBlank(status)){
			query.setInteger("status", Integer.parseInt(status));
			queryCount.setInteger("status", Integer.parseInt(status));
		}
		BigInteger bi = (BigInteger)queryCount.uniqueResult();
		page.setRecords(bi.longValue());
		query.setFirstResult(page.getFirstResult());
		query.setMaxResults(page.getMaxResults());
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		page.setRows(query.list());
		return page;
	}
	
	/**
	 * @category 根据id获取对象
	 * @date 2015年7月13日
	 * @return page
	 */
	@Override
	public DicEntprodProfile getDicEntprodProfileById(String dicEntprodProfileId){
		Session session = sessionFactory.getCurrentSession();
		Query query = session.createQuery(" from DicEntprodProfile where dicEntprodProfileId = :dicEntprodProfileId ");
		query.setString("dicEntprodProfileId", dicEntprodProfileId);
		return (DicEntprodProfile)query.uniqueResult();
	}
	/**
	 * @category 停用启用
	 * @date 2015年7月13日
	 * @return page
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void changeStatus(DicEntprodProfile dicEntprodProfile){
		Session session = getSession();
		List<String> list = new ArrayList<String>();
		if("0".equals(dicEntprodProfile.getStatus()+"")){
			StringBuffer sb = new StringBuffer()
			.append("select dic_entprod_profile_id from dic_entprod_profile where dic_entprod_profile_id= :dicEntprodProfileId  ");
			Query query = session.createSQLQuery(sb.toString());
			query.setString("dicEntprodProfileId", dicEntprodProfile.getDicEntprodProfileId());
			List<Object> data = query.list();
			for(int i = 0;i<data.size();i++){
				list.add(data.get(i).toString());
			}
		}
		StringBuffer sql = new StringBuffer();
		sql.append(" update dic_entprod_profile set status= :status,upd_datetime= :updDatetime, ")
		   .append(" upd_user= :updUser where dic_entprod_profile_id= :dicEntprodProfileId     ");
		Query update = session.createSQLQuery(sql.toString());
		update.setLong("status",dicEntprodProfile.getStatus());
		update.setTimestamp("updDatetime", new Date());
		update.setString("updUser", dicEntprodProfile.getUpdUser());
		update.setString("dicEntprodProfileId", dicEntprodProfile.getDicEntprodProfileId());
		update.executeUpdate();
		session.flush();
		writeLog(dicEntprodProfile,list);
	}
	
	/**
	 * @category  写日志
	 * @date 2015年7月13日
	 * @return page
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void writeLog(DicEntprodProfile dicEntprodProfile,List<String> idList){
		Session session = getSession();
		StringBuffer detail = new StringBuffer();
		if(!"0".equals(dicEntprodProfile.getStatus()+"")){
			StringBuffer sb = new StringBuffer()
			.append(" select first_level_indi_name firstLevelIndiName,remark remark,status from dic_entprod_profile where dic_entprod_profile_id= :dicEntprodProfileId ")
			.append(" UNION all ")
			.append(" select t.* from (select first_level_indi_name firstLevelIndiName,remark remark,status from dic_entprod_profile_log where dic_entprod_profile_id= :dicEntprodProfileId order by upd_datetime desc limit 1) t ");
			Query query1 = session.createSQLQuery(sb.toString());
			query1.setString("dicEntprodProfileId",dicEntprodProfile.getDicEntprodProfileId());
			query1.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
			List<Map<String,Object>> list = query1.list();
			
			if(list.size()==1){
				detail.append("新增药品资质类型<br/>名称：")
			      .append(list.get(0).get("firstLevelIndiName").toString())
			      .append("<br/>备注：")
			      .append(list.get(0).get("remark").toString());
			}else{
				if(!list.get(0).get("firstLevelIndiName").toString().equals(list.get(1).get("firstLevelIndiName").toString())){
					detail.append("药品资质类型名称由")
					      .append(list.get(1).get("firstLevelIndiName").toString())
					      .append("变为")
					      .append(list.get(0).get("firstLevelIndiName").toString());
				}
				if(list.get(1).get("remark") != null ){
					if(!list.get(0).get("remark").toString().equals(list.get(1).get("remark").toString())){
						detail.append("<br/>备注由")
						      .append(list.get(1).get("remark").toString())
						      .append("变为")
						      .append(list.get(0).get("remark").toString());
					}
				}else{
					
				}
				
				if(!list.get(0).get("status").toString().equals(list.get(1).get("status").toString())){
					detail.append("<br/>状态由")
					      .append("1".equals(list.get(1).get("status").toString())?"启用":"停用")
					      .append("变为")
					      .append("1".equals(list.get(0).get("status").toString())?"启用":"停用");
				}
				
				if(detail.indexOf("<br/>")==0){
					detail.delete(0, 5);
				}
			}
			
		}
		
		StringBuffer sql = new StringBuffer();
		sql.append(" insert into dic_entprod_profile_log(log_id,dic_entprod_profile_id,first_level_indi_code,first_level_indi_name, status, remark,upd_datetime,upd_user,detail) select  UUID(),t.*,:detail from dic_entprod_profile t where t.dic_entprod_profile_id= :dicEntprodProfileId");
		
		if("0".equals(dicEntprodProfile.getStatus()+"")){
			sql.append(" or t.dic_entprod_profile_id in (:idList)");
			detail.append("状态由启用变为停用");
		}
		Query query = session.createSQLQuery(sql.toString());
		query.setString("dicEntprodProfileId", dicEntprodProfile.getDicEntprodProfileId());
		query.setString("detail", detail.toString());
		if("0".equals(dicEntprodProfile.getStatus()+"")){
			query.setParameterList("idList", idList);
		}
		query.executeUpdate();
		session.flush();
	}
	
	
	/**
	 * @category  新增或修改
	 * @date 2015年7月13日
	 * @return page
	 */
	@Override
	public void dicEntprodProfileUpdate(Pagination page){
		Session session = sessionFactory.getCurrentSession();
		DicEntprodProfile dicEntprodProfile = (DicEntprodProfile) page.getForm();
		if(StringUtils.isNotBlank(dicEntprodProfile.getDicEntprodProfileId())){
			StringBuffer sql = new StringBuffer();
			sql.append("update dic_entprod_profile set first_level_indi_name = :firstLevelIndiName,remark = :remark,upd_datetime = :updDatetime,upd_user = :updUser where dic_entprod_profile_id = :dicEntprodProfileId ");
			Query query = session.createSQLQuery(sql.toString());
			query.setString("firstLevelIndiName", dicEntprodProfile.getFirstLevelIndiName());
			query.setString("remark", dicEntprodProfile.getRemark());
			query.setString("updUser", dicEntprodProfile.getUpdUser());
			query.setString("dicEntprodProfileId", dicEntprodProfile.getDicEntprodProfileId());
			query.setString("updDatetime", dicEntprodProfile.getUpdDatetime());
			query.executeUpdate();
			session.flush();
			writeLog(dicEntprodProfile,null);
		}else{
			String uuid = UUID.randomUUID().toString();
			StringBuffer sql = new StringBuffer();
			sql.append("insert into dic_entprod_profile SELECT :uuid,")
			   .append(" CONCAT(LEFT(MAX(first_level_indi_code),(CHAR_LENGTH(MAX(first_level_indi_code))-CHAR_LENGTH((RIGHT(MAX(first_level_indi_code),9)+1)))),(RIGHT(MAX(first_level_indi_code),9)+1)) t ,")
			   .append(":firstLevelIndiName,1,:remark,:updDatetime,:updUser FROM dic_entprod_profile ");
			Query query = session.createSQLQuery(sql.toString());
			query.setString("uuid", uuid);
			query.setString("firstLevelIndiName", dicEntprodProfile.getFirstLevelIndiName());
			query.setString("remark", dicEntprodProfile.getRemark());
			query.setString("updUser", dicEntprodProfile.getUpdUser());
			query.setString("updDatetime", dicEntprodProfile.getUpdDatetime());
			query.executeUpdate();
			session.flush();
			dicEntprodProfile.setDicEntprodProfileId(uuid);
			writeLog(dicEntprodProfile,null);
		}
	}

	/**
	 * @category  检查重复
	 * @date 2015年7月13日
	 * @return page
	 */
	@Override
	public Integer checkRepeat(Pagination page){
		Session session = sessionFactory.getCurrentSession();
		DicEntprodProfile dicEntprodProfile = (DicEntprodProfile) page.getForm();
		StringBuffer sql = new StringBuffer();
		sql.append(" 	select count(*) from dic_entprod_profile where first_level_indi_name=:firstLevelIndiName           ")
		   .append("    and dic_entprod_profile_id <> :dicEntprodProfileId   ");
		Query query = session.createSQLQuery(sql.toString());
		query.setString("firstLevelIndiName", dicEntprodProfile.getFirstLevelIndiName());
		query.setString("dicEntprodProfileId", dicEntprodProfile.getDicEntprodProfileId());
		return Integer.parseInt(query.uniqueResult().toString());
	}

	/**
	 * @category  药品资质类型编辑
	 * @date 2015年7月13日
	 * @return page
	 */
	@Override
	public void updateEntprodProfile(Pagination page) {
		String dicEntprodProfileId = page.getConditions().get("dicEntprodProfileId");
		String msg = compareData(dicEntprodProfileId,page);
		if (StringUtils.isNotBlank(msg)){
			String firstLevelIndiName = page.getConditions().get("firstLevelIndiName");
			String remark = page.getConditions().get("remark");
			String updUser = page.getConditions().get("updUser");
			StringBuffer sql = new StringBuffer();
			sql.append("update dic_entprod_profile set first_level_indi_name = :firstLevelIndiName,remark = :remark,upd_datetime = :updDatetime,upd_user = :updUser where dic_entprod_profile_id = :dicEntprodProfileId ");
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("dicEntprodProfileId", dicEntprodProfileId);
			params.put("firstLevelIndiName",firstLevelIndiName );
			params.put("remark",remark );
			params.put("updUser",updUser );
			params.put("updDatetime", new Date());
			dao.executeSql(sql.toString(), params);
			String logsql = "  insert into dic_entprod_profile_log(log_id,dic_entprod_profile_id,first_level_indi_code,first_level_indi_name, status, remark,upd_datetime,upd_user,detail) select  UUID(),t.*,:msg from dic_entprod_profile t where t.dic_entprod_profile_id= :dicEntprodProfileId ";
			params.put("msg", msg);
			params.remove("firstLevelIndiName");
			params.remove("remark");
			params.remove("updUser");
			params.remove("updDatetime");
			dao.executeSql(logsql, params);

		}

	}

	private String compareData(String id, Pagination page) {
		String sql = "select * from dic_entprod_profile where dic_entprod_profile_id = :dicEntprodProfileId";
		Map<String, Object> params = new HashMap<String, Object>();
		String dicEntprodProfileId = page.getConditions().get("dicEntprodProfileId");
		params.put("dicEntprodProfileId", dicEntprodProfileId);
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> list = (List<Map<String, Object>>) dao.getSqlMapList(sql, params);
		if (null != list && list.size() > 0){
			Map<String, Object> map = list.get(0);
			String firstLevelIndiName = page.getConditions().get("firstLevelIndiName");
			String remark = page.getConditions().get("remark");
			StringBuffer msg = new StringBuffer();
			if (! firstLevelIndiName.equals(map.get("first_level_indi_name").toString())){
				msg.append("药品资质类型名称由")
				.append(map.get("first_level_indi_name").toString())
				.append("变为")
				.append(firstLevelIndiName)
				.append("<br/>");
			}
			if (! remark.equals(map.get("remark").toString())){
				msg.append("备注由")
				.append(map.get("remark").toString())
				.append("变为")
				.append(remark)
				.append("<br/>");
			}
			return msg.toString();
		}
		
		return null;
	}

	/**
	 * @category  药品资质类型新增
	 * @date 2015年7月13日
	 * @return page
	 */
	@Override
	public void addEntprodProfile(Pagination page) {
		String dicEntprodProfileId = page.getConditions().get("dicEntprodProfileId");
		String firstLevelIndiName = page.getConditions().get("firstLevelIndiName");
		String remark = page.getConditions().get("remark");
		String updUser = page.getConditions().get("updUser");
		String uuid = page.getConditions().get("uuid");
		
		StringBuffer sql = new StringBuffer();
		sql.append("insert into dic_entprod_profile SELECT :uuid,")
		   .append(" CONCAT(LEFT(MAX(first_level_indi_code),(CHAR_LENGTH(MAX(first_level_indi_code))-CHAR_LENGTH((RIGHT(MAX(first_level_indi_code),9)+1)))),(RIGHT(MAX(first_level_indi_code),9)+1)) t ,")
		   .append(":firstLevelIndiName,1,:remark,:updDatetime,:updUser FROM dic_entprod_profile ");
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("dicEntprodProfileId", dicEntprodProfileId);
		params.put("firstLevelIndiName", firstLevelIndiName);
		params.put("remark", remark);
		params.put("updUser", updUser);
		params.put("updDatetime", new Date());
		params.put("uuid", uuid);
		dao.executeSql(sql.toString(), params);
		String logsql = "  insert into dic_entprod_profile_log(log_id,dic_entprod_profile_id,first_level_indi_code,first_level_indi_name, status, remark,upd_datetime,upd_user,detail) select  UUID(),t.*,:msg from dic_entprod_profile t where t.dic_entprod_profile_id= :dicEntprodProfileId ";
		params.put("msg", "新增药品资质类型");
		params.remove("firstLevelIndiName");
		params.remove("remark");
		params.remove("updUser");
		params.remove("updDatetime");
		params.remove("uuid");
		dao.executeSql(logsql, params);
	}
	
	
	/**
	 * name查看有无重复数据
	 * @param name
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@Override
	public List<DicEntprodProfile> getSpecBy(String key, String value,String dicEntprodProfileId) {
		StringBuffer sql = new StringBuffer();
		sql.append("select * from dic_entprod_profile where ")
		   .append(key)
		   .append(" = ? and  dic_entprod_profile_id <> ? ");
		Query query = getSession().createSQLQuery(sql.toString());
		query.setParameter(0, value);
		query.setParameter(1,dicEntprodProfileId);
		return query.list();
	}
	
	/**
	 * 根据条件获取不分页数据
	 * @param page
	 * @return page
	 */
	@Override
	public Pagination getDicEntprodProfileNoPage(Pagination page){
		String indiName = page.getConditions().get("indiName");
		String status = page.getConditions().get("status");
		StringBuffer sql = new StringBuffer();
		sql.append(" select d.first_level_indi_code firstLevelIndiCode,d.first_level_indi_name firstLevelIndiName,case d.status when '0' then '停用' else '启用' end status from dic_entprod_profile d where 1=1 ");
		if(StringUtils.isNotBlank(indiName)){
			sql.append(" and d.first_level_indi_name like :indiName ");
		}
		if(StringUtils.isNotBlank(status)){
			sql.append(" and d.status = :status ");
		}
		Query query = getSession().createSQLQuery(sql.toString());
		if(StringUtils.isNotBlank(indiName)){
			query.setString("indiName", "%" + indiName + "%");
		}

		if(StringUtils.isNotBlank(status)){
			query.setInteger("status", Integer.parseInt(status));
		}
		query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		List<?> list = query.list();
		
		page.setRows(list);

		return page;
	}
}	